<script setup lang="ts">
import { ref, onMounted,reactive, UnwrapRef, computed } from 'vue'
import { liveOpenList, liveOpenDelete } from '../../stores/api/openClass'
import { useCounterStore } from '../../stores/counter'
import { useRoute, useRouter } from "vue-router";
import type { TableProps } from 'ant-design-vue';
import { ImgUrlPrefix } from '../../utils/config';
import { message } from 'ant-design-vue';
import { QuestionCircleOutlined } from '@ant-design/icons-vue';
import clipboard3 from 'vue-clipboard3';
import pseudoLive from './pseudoLive.vue';
import { h5Url } from '../../utils/config'
const store = useCounterStore()
const router:any = useRouter()
const route:any = useRoute()
const loading = ref(false)
const isShowAttachment = ref(false)
const attachment = ref([])
const { toClipboard } = clipboard3()
const isShowVideo = ref<boolean>(false)
const video_url = ref<string>('')
const start_time = ref<number>(0)

const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
});
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',   
    width: 90
  },
  {
    title: '视频时长',
    dataIndex: 'video_time',
    key: 'video_time'
  },
  {
    title: '开始时间',
    dataIndex: 'start_time',
    key: 'start_time',
  },
  {
    title: '结束时间',
    dataIndex: 'end_time',
    key: 'end_time',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
  },
  {
    title: '更新时间',
    dataIndex: 'updated_at',
    key: 'updated_at',
  },
  {
    title: 'H5链接',
    dataIndex: 'url_h5',
    key: 'url_h5'
  },
//   {
//     title: '作业介绍',
//     dataIndex: 'desc',
//     key: 'desc',
//   },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
  },
];
const data_list = ref([])

interface FormState {
  title: string;
  status: string;
  type: string;
}
const formState: UnwrapRef<FormState> = reactive({
  title: '',
  status: '', 
  type: ''
});

// 公开课列表
const getOpenLiveList = () => {
    loading.value = true
    liveOpenList({ page:  pagination.current, title: formState.title, status: formState.status}, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            data_list.value = res.data.items
            pagination.total = res.data.total
        }
        loading.value = false
    }).catch((err: any) => {
        console.log(err)
        loading.value = false
    })
}

const openClassList = computed(() => {
  return data_list.value.map(item => {
       return { ...item,video_time: item.video_time ? secondsToTime(item.video_time) : 0,  created_at: store.timestampChangDate(item.created_at * 1000), updated_at: store.timestampChangDate(item.updated_at * 1000) ,start_time: store.timestampChangDate(item.start_time * 1000), end_time: store.timestampChangDate(item.end_time * 1000), url_h5: h5Url+'/#/pages/openClass/index?id='+ item.id }
  })
})

// 转换为时分秒
const secondsToTime = (seconds) => {
  let hours:any = Math.floor(seconds / 3600);
  let minutes:any = Math.floor((seconds % 3600) / 60);
  let secs:any = seconds % 60;
  hours = hours < 10 ?  '0' + hours : hours
  minutes = minutes < 10 ?  '0' + minutes : minutes
  secs = secs < 10 ?  '0' + secs : secs
  return `${hours}:${minutes}:${secs}`;
}

// 图片地址拼接
const getImgUrl = (val) => {
    const url = ImgUrlPrefix(val)
    return url
}

// 截取字符串
const getExtractString = (val) => {
    if(val) {
        const startIndex = val.indexOf('/') + 1
        const url = val.substring(startIndex);
        return url
    } else{
        return ''
    }
}

// 搜索
const onSubmit = () => {
    getOpenLiveList()
}
// 取消
const onCancel = () => {
    formState.title = ''
    formState.status = ''
    formState.type = ''
    getOpenLiveList()
}

const handleTableChange: TableProps['onChange'] = (
  pag: { pageSize: number; current: number }
) => {
  console.log(pag?.current)
  pagination.current = pag?.current
  getOpenLiveList()
};

// 删除
const handleDelete = (val:any) => {
    console.log(val)
    liveOpenDelete({ id: val.id}, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            message.success('删除成功');
            getOpenLiveList()
        } else {
            message.error(res.msg);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 查看
const handleSee = (val:any) => {
    // router.push({path: '/pseudoLive', query: { url: val.video_url, start_time: new Date(val.start_time).getTime() }})
    isShowVideo.value = true
    video_url.value = val.video_url
    start_time.value =  new Date(val.start_time).getTime()
}

// 创建公开课
const onAdd = () => {
    router.push({path: '/addOpenClass',query: {}})
}

const abc = (record) => {
    window.open(record.url_h5, '_blank');
}
//复制
const copy = async (text) => {
  try {
    await toClipboard(text);
    message.success('复制成功');
  } catch (error) {
    console.error(error);
  }
}

const backChange = () => {
    isShowVideo.value = false
}
onMounted(() => {
    getOpenLiveList()
})
</script>

<template>
    <div class="courseDetails">
        <div class="list-box">
            <div class="form-filter">
                <a-button type="primary" class="btn-ss" @click="onAdd">创建公开课</a-button>
                <!-- <a-form layout="inline" :model="formState">
                    <a-form-item label="作业标题">
                        <a-input v-model:value="formState.title" placeholder="请输入标题" />
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-select v-model:value="formState.status" placeholder="请选择状态" style="width: 130px">
                            <a-select-option :value="10">进行中</a-select-option>
                            <a-select-option :value="20">已结束</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item>
                        <a-button type="primary" class="btn-ss" @click="onSubmit">搜索</a-button>
                        <a-button style="margin: 0 20px;" @click="onCancel">取 消</a-button>
                    </a-form-item>
                </a-form> -->
            </div>
            <!-- :scroll="{ x: 1500}" -->
            <a-table :columns="columns" :pagination="pagination" 
                :loading="loading" :data-source="openClassList" @change="handleTableChange">
                <template #bodyCell="{ column, record }">
                    
                    <template v-if="column.key === 'id'">
                        <span>
                        {{ record.id }}
                        </span>
                    </template>
                    <template v-if="column.key === 'video_time'">
                        <span>
                        {{ record.video_time ? record.video_time : ''}}
                        </span>
                    </template>
                    <template v-if="column.key === 'start_time'">
                        <span>
                        {{ record.start_time || "--" }}
                        </span>
                    </template>
                    <template v-if="column.key === 'end_time'">
                        <span>
                        {{ record.end_time || "--" }}
                        </span>
                    </template>
                    <template v-if="column.key === 'created_at'">
                        <span>
                        {{ record.created_at || '--' }}
                        </span>
                    </template>
                    <template v-if="column.key === 'updated_at'">
                        <span>
                        {{ record.updated_at || '--' }}
                        </span>
                    </template>
                    <template v-if="column.key === 'deadline'">
                        <span>
                        {{ record.deadline || '--' }}
                        </span>
                    </template>
                    <template v-if="column.key === 'url_h5'">
                        <span>
                            <!-- <a v-if="record.url_h5" :href="record.url_h5" target="_blank" rel="noopener noreferrer"> {{  record.url_h5 }} </a> -->
                            <span v-if="record.url_h5"> <a>{{  record.url_h5 }}</a> <a-tag color="default" style="cursor: pointer" @click="copy(record.url_h5)">复制</a-tag></span>
                            <span v-else>--</span>
                        </span>
                    </template>
                    <!-- <template v-if="column.key === 'desc'">
                        <a-tooltip placement="top" v-if="record.desc.length > 40">
                            <template #title>
                                 <span>{{ record.desc }}</span>
                            </template>
                            <span>
                               {{ record.desc }}
                            </span>
                        </a-tooltip>
                        <span v-else>
                            {{ record.desc }}
                        </span>
                    </template> -->
                    <template v-else-if="column.key === 'action'">
                        <span style="margin-right: 10px">
                            <a-popconfirm title="是否删除吗？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(record)"> 
                                <template #icon><question-circle-outlined style="color: red" /></template>
                                <a>删除</a>
                            </a-popconfirm>
                          <!-- <a @click="handleDelete(record)">删除</a> -->
                        </span>
                        <span style="margin-right: 10px">
                          <a @click="handleSee(record)">查看</a>
                        </span>
                    </template>
                </template>
            </a-table>
        </div>
        <a-modal v-model:open="isShowAttachment" :title="'附件'" width="700px" ok-text="" cancel-text="" :footer="null">
            <div class="live-left">
                <div v-for="item in attachment" :key="item">
                    <a :href="getImgUrl(item)" rel="noopener noreferrer"> {{  getExtractString(item) }}</a>
                </div>
            </div>
        </a-modal>
        <pseudoLive :isShowVideo="isShowVideo" :video_url="video_url" :start_time="start_time" @backChange="backChange"></pseudoLive>
    </div>
</template>

<style scoped>
.courseDetails{
    padding: 15px;
}
.top-content-p{
    background-color: #fff;
    /* padding: 10px 15px;
    border-radius: 6px; */
}
.title-item-p{
    line-height: 40px;
    font-weight: bold;
    font-size: 16px;
}
.content-box{
    display: flex;
    flex-wrap: wrap;
    margin: 6px 0;
}
.name-item{
    line-height: 36px;
    min-width: 200px;
    color: #333;
    margin-right: 50px;
}
.name-item span{
    color: #000;
    margin-left:4px;
}
.content-ssv{
    color: #000;
    margin-left:4px;
}
.btn-ss{
    background-color: #fe5d26;
    height: 32px;
}
.btn-ss:hover{
    background-color: #fe5d26;
}
.btn-sub{
    background-color: #87d068;
    height: 32px;
}
.btn-sub:hover{
    background-color: #87d068;
}
.list-box{
    margin-top: 15px;
}

.form-filter{
   margin: 20px 0;   
   display: flex;
   justify-content: space-between;
}
.thumbnail_{
    width: 80px;
}
.cover-g{
    /* background-color: rgb(51,52,63); */
    width: 130px;
    height: 132px;
    line-height: 26px;
    text-align: center;
    padding: 10px 0;
    border-radius: 10px;
}
.cover-image{
    width: 100%;
    height: 100%;
}
.cover-image img{
    width: 100%;
    height: 100%;
}
</style>
